import api from "../../common/api.js";
import p from "../../utils/platform";
import constant from "../../common/constant";
import locationBehavior from "./../../behaviors/location";
import * as transferData from "../../models/transferData.js";
import { gioBaseLog, gioCooperationLog, gioNewUserLog } from "../../common/gioHandler.js";
import { authorizationBehavior } from "../../behaviors/authorization.js";

var app = getApp();
Page({
  behaviors: [locationBehavior, authorizationBehavior],
  data: {
    targetUnionId: '', //直接打开聊天页
    inviterInfo: {}, //邀请人信息
    retainPageVisible: false, //新人好礼挽留弹层
    isAuth: false, // 用户是否授权用户信息
    fissionDetailVisible: false, //显示裂变红包优惠券
    isShowNewCooperation: false,
    newUser: 0, // 是否新手
    offlinePaperState: 0, //地推红包校验状态 0没有 1有
    banner_active_name: "", //当前banner活动名称
    isFirstState: true, //是否是第一次进入页面
    editDialog: false, //完善头像名称显示隐藏

    needShowEdit: false, //需要从登录页返回后拉起完善头像弹窗
    posterState: true, //海报图标显示隐藏
    mobile: "",
    custNum: 0, //导入客户数
    isUpdate: false,
    showDialog: false, //tabBar添加显示隐藏
    hidden: false,
    tabConentIndex: 0, //默认显示的tabbar index
    isShowTabActivity: true,
    tabBarObj: [
      {
        tabBarName: "首页",
        tabGioName: constant.HOME_PAGE_VIEW,
        tabBarIcon: "../../images/icon_01.png",
        tabBarIconActive: "../../images/icon_01_active.png",
        isRedPoint: false,
        bubble: "", //气泡
      },
      {
        tabBarName: "获客",
        tabGioName: constant.VISITOR_PAGE_VIEW,
        tabBarIcon: "../../images/icon_02.png",
        tabBarIconActive: "../../images/icon_02_active.png",
        isRedPoint: false,
        bubble: "",
      },
      {
        tabBarName: "消息",
        tabGioName: constant.IM_PAGE_VIEW,
        tabBarIcon: "../../images/icon/im.png",
        tabBarIconActive: "../../images/icon/im2.png",
        isRedPoint: false,
        bubble: "",
      },
      {
        tabBarName: "合作",
        tabGioName: constant.COOPERATION_PAGE_VIEW,
        tabBarIcon: "../../images/icon_02_old.png",
        tabBarIconActive: "../../images/icon_02_active_old.png",
        isRedPoint: false,
        bubble: "",
      },
      {
        tabBarName: "我的",
        tabGioName: constant.MY_PAGE_VIEW,
        tabBarIcon: "../../images/icon_04.png",
        tabBarIconActive: "../../images/icon_04_active.png",
        isRedPoint: false,
        bubble: "",
      },
    ],
    readLength: [], //新访客数
    agentId: "", //当前经纪人id
    options: "", //进入的参数
    height: 0, //导航栏的高度
    redFission: false, //红包裂变用户
    detainment: false, //web端未登录后的挽留
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    console.log("##index页面的options##", options);
    wx.showShareMenu({
      withShareTicket: true,
      menus: ["shareAppMessage", "shareTimeline"],
    });
    if (options.visitorTab) {
      transferData.setData("visitorsDefaultTab", options.visitorTab);
    }

    app.globalData.indexPage = this;
    // 统一为更新
    this.data.isUpdate = true;

    p.showLoading({ title: "载入中...", mask: true });
    setTimeout(() => {
      p.hideLoading();
    }, 1600);

    app.globalData.loginPromise.then(({ sessionUser }) => {
      this.fissionIncident(options);

      this.isHaveHouse();
      wx.removeStorageSync("lufangtiaozhuan");
      this.data.options = options;
      var that = this;
      if (that.data.isUpdate) {
        that.selectComponent("#home").changeList(2);
      }

      this.previewTab(options);

      const needShowEdit = app.globalData.needShowEdit;
      app.globalData.needShowEdit = 0;
      if ((options && options.needShowEdit) || needShowEdit) {
        that.setData({
          editDialog: true,
        });
      }
      if (options.stat == 1) {
        that.selectComponent("#home").changeList(1);
      }

      app.mobileReadyCallback = (res) => {
        if (
          res.data.content.sessionUser.mobile == null ||
          res.data.content.sessionUser.mobile == "" ||
          res.data.content.sessionUser.extProps.nickname == null ||
          res.data.content.sessionUser.extProps.wechatUnionid == null ||
          res.data.content.sessionUser.extProps.wxHeadImg == null
        ) {
          if (!this.data.isFirstState) {
            if (that.data.needShowEdit) {
              wx.redirectTo({
                url: "/pages/startPage/startPage?needShowEdit=1",
              });
            } else {
              wx.redirectTo({
                url: "/pages/startPage/startPage",
              });
            }
          }
        } else {
          that.setNavigationBarTitle();
        }
      };

      wx.nextTick(() => {
        this.compareInterviewTime();
      });
      this.queryPmReferenceDetailInfoByRefCode();

      this.bubbleHandler();
    });
  },

  // 拉新裂变活动
  fissionIncident(options) {
    // 扫描二维码
    const info = app.globalData.querySceneInfo
    // 邀请方式
    this.data.antreVar = options.antreVar

    // 跳转链接里带有MEMBERFISSION时跳出裂变的红包
    if (options.activityCode == "MEMBERFISSION") {
      this.fissionIncidentNext(options.fromUserId);

    } else if (info) {
      app.resetQueryScene()

      if (info.activityCode === 'MEMBERFISSION') {
        this.data.antreVar = info.antreVar;
        this.fissionIncidentNext(info.fromUserId);
      } else {
        this.fissionIncidentNext(null);
      }

    } else {
      this.fissionIncidentNext(null);
    }
  },

  // 拉新裂变的处理 (fromUserId 空 则表示通过搜索小程序进来)
  fissionIncidentNext(fromUserId) {
    if (fromUserId) {
      api.relationshipAdd({ inviteUserId: fromUserId }, ({ data }) => {
        if (!data.content) return;
        const { condition, nickName, avatar } = data.content;
        switch (condition) {
          case 1:
            wx.navigateTo({ url: "/pages/mine/newInvite/newFissionPage/newFissionPage" });
            break;

          case 2:
            wx.showToast({
              title: "您已是树懒老用户，邀请好友可获得现金奖励！",
              icon: "none",
            });
            setTimeout(() => {
              wx.navigateTo({ url: "/pages/mine/newInvite/newFissionPage/newFissionPage" });
            }, 2000);

            break;
          case 3:
            this.setData({
              redFission: true,
              inviterInfo: {
                nickName,
                avatar,
                fromUserId,
              },
            });
            
            gioNewUserLog(constant.Open_First_Page, fromUserId, this.data.antreVar, constant.first);

            break;
        }
      });
    } else {
      // 老用户则不需要调用
      if (app.isOldUser()) return;
      api.checkMemberFessionWindow(null, ({ data }) => {
        if (!data.content) return;
        const { needWindow, nickName, avatar, fromUserId } = data.content;
        if (needWindow == 1) {
          this.setData({
            redFission: true,
            inviterInfo: {
              nickName,
              avatar,
              fromUserId
            },
          });

          gioNewUserLog(constant.Open_First_Page, fromUserId, this.data.antreVar, constant.notfirst);
        }
      });
    }
  },

  handleReceiveFissionRed() {
    gioNewUserLog(constant.Click_Money, this.data.inviterInfo.fromUserId, this.data.antreVar);

    this.comfirmReceiveFissionRed()
  },

  // 准备领取礼包（弹出第二个弹层）
  comfirmReceiveFissionRed() {
    app.globalData.loginPromise.then(({ sessionUser }) => {
      const cb = () => {
        api.releaseNewMemberReward(null, ({ data }) => {
          if (data.isSuccess) {
            gioNewUserLog(constant.View_Coupons, this.data.inviterInfo.fromUserId, this.data.antreVar);

            this.setData({
              redFission: false,
              fissionDetailVisible: true,
            });
          }
        })
      };

      app
        .mobileLogin()
        .then(() => {
          cb();
        })
        .catch(() => {
          app.globalData.afterMobileAuthorCallBack = () => {
            wx.navigateBack();
            cb();
          };
        });
    });
  },

  // 预览特定的标签页
  previewTab(options) {
    // 通过固定索引
    if (options.tabConentIndex) {
      if (options.pageFrom) {
        app.globalData.pageFrom = options.pageFrom
      }
      this.setData({
        tabConentIndex: parseFloat(options.tabConentIndex),
        targetUnionId: options.gzh_unionid || ''
      });

      let i = this.data.tabBarObj.findIndex((v) => v.tabBarName == "我的");
      let cooperationIndex = this.data.tabBarObj.findIndex((v) => v.tabBarName == "合作");
      if (options.tabConentIndex == i || options.tabConentIndex == cooperationIndex) {
        this.setNavigationBarTitle();
      }

      // 通过tab名称
    } else if (options.tabConentName) {
      let i = this.data.tabBarObj.findIndex((v) => v.tabBarName == options.tabConentName);
      if (i > -1) {
        this.setData({ tabConentIndex: i });
        this.setNavigationBarTitle();
      }
    }
  },

  // 关闭地推红包
  handleOnOffineRedpaperClose(e) {
    this.setData({
      offlinePaperState: false,
    });
  },

  handleMaidian(e) {
    this.data.banner_active_name = e.detail;
  },
  cancelLoc() {
    this.setData({
      hidden: false,
    });
  },
  confirmLoc() {
    this.setData({
      hidden: false,
    });
    wx.openSetting({
      success(res) {
      },
    });
  },
  toggleDialog() {
    this.setData({
      showDialog: !this.data.showDialog,
    });
  },
  freeBack: function () {
    var that = this;
    that.setData({
      showDialog: !this.data.showDialog,
    });
  },

  //我的信息保存按钮调用的方法，
  getAllnumber() {
    return new Promise((res, rej) => {
      var that = this;
      that
        .selectComponent("#setting")
        .getSessionInfo()
        .then(() => {
          res();
        });
    });
  },

  goTOto() {
    wx.requestSubscribeMessage({
      tmplIds: ["P8NAay-gJ16j7zhWuNWgMH4L_ee55CpuWt2bAEhWnpg"],
      success(res) {
        for (var key in res) {
          if (key != "errMsg") {
            if (res[key] == "reject") {
              wx.showModal({
                title: "订阅消息",
                content: "您已拒绝了订阅消息，如需重新订阅请前往设置打开。",
                confirmText: "去设置",
                //showCancel: false,
                success: (res) => {
                  if (res.confirm) {
                    wx.openSetting({});
                  }
                },
              });
              return;
            } else {
              wx.showToast({
                title: "订阅成功",
              });
            }
          }
        }
      },
      fail(res) {
        wx.showModal({
          title: "订阅消息",
          content: "您关闭了“接收订阅信息”，请前往设置打开！",
          confirmText: "去设置",
          showCancel: false,
          success: (res) => {
            if (res.confirm) {
              wx.openSetting({});
            }
          },
        });
      },
    });
  },
  //跳转新增房源
  goChooseHouse() {
    wx.navigateTo({
      url: "/pages/addHouse/chooseHouse/chooseHouse",
    });
  },

  //跳转创建店组
  goAddShopGroup() {
    wx.setStorageSync("editstate", "");
    wx.showToast({
      icon: "none",
      title: "暂未开通，敬请期待",
      duration: 2000,
      success: function () {
        setTimeout(function () {
          wx.hideToast();
        }, 2000);
      },
    });
  },
  // 判断是否有房源
  isHaveHouse() {
    app.checkHouses().then((res) => {
      this.setData({
        haveHouse: app.globalData.checkHouses ? 2 : 1,
      });
    });
  },
  // tabbar点击跳转
  goTabBar(e) {
    let t = this;
    if (t.data.isShowTabActivity) {
      t.setData({
        isShowTabActivity: false,
      });
    }
    const index = parseInt(e.currentTarget.dataset.index);
    let i = this.data.tabBarObj.findIndex((v) => v.tabBarName == "我的");
    if (index == 0 || index == i) {
      let mobile = app.globalData.sessionUser.mobile;
      if (mobile) {
        app.getMemberPower();
        this.isHaveHouse();
      }
    }
    if (this.data.tabConentIndex == index) return;
    app.globalData.hold = false;
    wx.setStorageSync("boole", true);
    this.setData({
      tabConentIndex: index,
      posterState: index != 0 ? false : true,
      hold: false,
    });
    this.setNavigationBarTitle();
  },
  //获取新导入客户(数)

  // 跳转到客源页面
  goWebView() {
    this.selectComponent("#home").guidanceBanner("小程序介绍");
  },

  // 跳转到录房页面
  goAddHouse() {
    this.selectComponent("#home").goChooseHouse();
  },

  // 跳转到个人店铺页面
  goShop() {
    wx.navigateTo({
      url: "/pages/mine/myShop/myShop",
    });
  },
  // 设置导航栏的高度
  getNavHeight() {
    this.setData({
      height: app.globalData.navHeight,
      top: app.globalData.navTop,
    });
  },
  closeKeFuAndHold() {
    this.closeHold();
    this.closekefu();
  },

  // 推荐功能气泡提示
  bubbleHandler() {
    if (app.globalData._wx_city == "上海市" && !wx.getStorageSync("_bubble_cooperation")) {
      let i = this.data.tabBarObj.findIndex((v) => v.tabBarName == "合作");
      this.setData({
        [`tabBarObj[${i}].bubble`]: "松江合作房源",
      });
    }
  },

  compareInterviewTime() {
    api.compareInterviewTime({}, (res) => {
      if (!res.data.content) return;
      if (res.data.content.compareInterviewTime) {
        let i = this.data.tabBarObj.findIndex((v) => v.tabBarName == "合作");
        if (i >= 0) {
          this.setData({
            [`tabBarObj[${i}].isRedPoint`]: true,
          });
        }
      }
    });
  },

  // 判断是否授权手机号
  isGetPhone() {
    if (!app.globalData.sessionUser.mobile) {
      this.setData({
        newUser: 1,
      });
    } else {
      this.setData({
        newUser: 2,
      });
    }
  },

  setNavigationBarTitle() {
    var that = this;
    this.setData({
      mobile: app.globalData.sessionUser.mobile,
    });

    let tabBarItem = this.data.tabBarObj[this.data.tabConentIndex];
    wx.setNavigationBarTitle({ title: tabBarItem.tabBarName });
    let curIndex = this.data.tabConentIndex;

    if (tabBarItem.tabGioName) {
      if (tabBarItem.tabGioName === constant.COOPERATION_PAGE_VIEW) {
        app.globalData.loginPromise.then(({ sessionUser }) => {
          gioCooperationLog(tabBarItem.tabGioName, sessionUser.id);
        })
      } else {
        gioBaseLog(tabBarItem.tabGioName)
      }
    }

    switch (tabBarItem.tabBarName) {
      case "首页":
        let boole = wx.getStorageSync("boole");
        if (boole == true) {
          var stat = wx.getStorageSync("currentStatus");
          wx.setStorageSync("boole", true);
          that.selectComponent("#home").changeList(stat);
        }
        break;

      case "获客":
        this.setData({
          [`tabBarObj[${this.data.tabConentIndex}].isRedPoint`]: false,
        });
        if (this.data.readLength) {
          api.updateReadStatus(
            {
              agentId: this.data.agentId,
              readStatus: 0,
            },
            (res) => {}
          );
        }

        break;

      case "消息":
        app.mobileLogin(false, "", false).catch(() => {
          app.globalData.afterMobileAuthorCallBack = () => {
            wx.redirectTo({ url: "/pages/index/index?tabConentIndex=" + curIndex });
          };
        });
        break;
      case "合作":
        // 已读设置
        if (tabBarItem.bubble) {
          wx.setStorageSync("_bubble_cooperation", true);
          this.setData({
            [`tabBarObj[${curIndex}].bubble`]: "",
          });
        }
        this.setData({
          [`tabBarObj[${this.data.tabConentIndex}].isRedPoint`]: false,
          [`tabBarObj[${this.data.tabConentIndex}].bubble`]: "",
        });
        app
          .mobileLogin(false, "", false)
          .then(() => {
            that.checkCooperationUserAuth();
          })
          .catch(() => {
            app.globalData.afterMobileAuthorCallBack = () => {
              wx.redirectTo({ url: "/pages/index/index?tabConentIndex=" + curIndex });
            };
          });
        break;

      case "我的":
        let mobile = app.globalData.sessionUser.mobile;
        let user = wx.getStorageSync("user");
        let res = getApp().globalData.loginUserInfo;
        if (!mobile || !user.nickname) {
          app
            .mobileLogin(null, "我的", false)
            .then(() => {
              wx.redirectTo({ url: "/pages/index/index?tabConentIndex=" + curIndex });
            })
            .catch(() => {
              app.globalData.afterMobileAuthorCallBack = () => {
                wx.redirectTo({ url: "/pages/index/index?tabConentIndex=" + curIndex });
                this.selectComponent("#setting").getSessionInfo();
              };
            });
          app.mobileReadyCallback && app.mobileReadyCallback(res);
        } else {
          this.selectComponent("#setting").getSessionInfo();
        }
        break;
    }
  },

  // 消息阅读
  handleReadMsg({ detail }) {
    let i = this.data.tabBarObj.findIndex((v) => v.tabBarName == "消息");
    this.setData({
      [`tabBarObj[${i}].isRedPoint`]: detail,
    });
  },
  onMyEvent(e) {
    this.setData({
      tabConentIndex: e.detail.tabConentIndex,
    });
  },
  onEvent(e) {
    this.setData({
      newUser: e.detail.newUser,
    });
  },
  scan() {
    wx.scanCode({
      success: (res) => {
        console.log("###top scan result###", res);
        if (['trial', 'develop'].indexOf(wx.getAccountInfoSync().miniProgram.envVersion) !== -1) {
          if(res && res.result && res.result.indexOf('pages/house/punchCard/punchCard') !== -1) {
            wx.redirectTo({
              url: res.result,
            })
            return
          }
        }
        const result = res.result;
        if (result && result.slice) {
          if (result.slice(0, 6) == "https:") {
            wx.navigateTo({
              url: "/pages/gatherHouse/scanAddHouse/scanAddHouse?scanCode=" + encodeURIComponent(result),
            });
          } else {
            wx.navigateTo({ url: "/pages/home/scanWeb/scanWeb?scanCode=" + result });
          }
        }
      },
    });
  },
  canScan() {
    app
      .mobileLogin(null, "首页")
      .then(() => {
        this.scan();
      })
      .catch(() => {
        app.globalData.afterMobileAuthorCallBack = () => {
          p.redirectTo({ url: "/pages/index/index" });
        };
      });
  },

  // 拒绝红包领取 展示挽留弹层
  closeIndexfission() {
    this.setData({
      redFission: false,
      retainPageVisible: true,
    });

    gioNewUserLog(constant.clickreject, this.data.inviterInfo.fromUserId, this.data.antreVar);

  },
  // 拒绝领取新人好礼
  handleJJHY() {
    this.setData({
      retainPageVisible: false,
    });

    gioNewUserLog(constant.clickrejectfriend, this.data.inviterInfo.fromUserId, this.data.antreVar);

    // 添加待办
    const { inviterInfo, antreVar } = this.data;
    const { fromUserId } = inviterInfo
    app.globalData.authorTodoList.push(() => {
      api.releaseNewMemberReward(null, ({ data }) => {
        if (data.isSuccess) {
          gioNewUserLog(constant.View_Coupons, fromUserId, antreVar);
        }
      })
    })
  },
  // 领取新人好礼
  handleLJLQ() {
    this.setData({
      retainPageVisible: false,
    });

    gioNewUserLog(constant.clickreceive, this.data.inviterInfo.fromUserId, this.data.antreVar);

    this.comfirmReceiveFissionRed();
  },

  closefissionRED() {
    this.setData({
      fissionDetailVisible: false,
    });
    gioNewUserLog(constant.clickexperience, this.data.inviterInfo.fromUserId, this.data.antreVar);
  },

  // 点击使用优惠券
  useFissionRED() {
    this.setData({
      fissionDetailVisible: false,
    });

    gioNewUserLog(constant.Click_Pay2, this.data.inviterInfo.fromUserId, this.data.antreVar);

    wx.navigateTo({
      url: "/pages/mine/memberCentre/memberCentre?orderEntr=shareCoupons",
    });
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    transferData.resetData("selectHouseAreaEnterNextPage");
    app.globalData.loginPromise.then(() => {
      this.checkCurrentCity();
      this.checkTopScanStatus();
      // 授权后隐藏首页新手引导
      if (app.globalData.sessionUser.mobile) {
        this.setData({
          newUser: app.globalData.newUser,
        });
      }
      var that = this;
      that.setNavigationBarTitle();
      if (that.data.isUpdate) {
        const index = wx.getStorageSync("currentStatus");
        that.selectComponent("#home").changeList(index);
      }
      api.getHouDelByReadStatus(
        {
          readStatus: 0,
        },
        (res) => {
          this.setData({
            ["tabBarObj[1].isRedPoint"]: res.data.content.length > 0 ? true : false,
            readLength: res.data.content.length,
            agentId: res.data.content.length > 0 ? res.data.content[0].agentId : "",
          });
        }
      );
      this.isHaveHouse();
      app.checkMobileHou().then(() => {
        if (!app.globalData.haveMoveHouse && app.globalData.hold) {
          this.setData({
            haveMoveHouse: app.globalData.haveMoveHouse,
            hold: app.globalData.hold,
          });
        } else {
        }
      });
      if (app.globalData.lastPage == "/pages/home/scanWeb/scanWeb" && app.globalData.needShowDetainment) {
        this.setData({
          detainment: true,
        });
      }
    });
  },
  onReady: function () {
    app.globalData.systemPromise.then(() => {
      this.getNavHeight();
    });
  },
  isFirstStateFunc(e) {
    this.setData({
      isFirstState: e.detail,
    });
  },
  closeEdit() {
    this.setData({
      editDialog: false,
    });
  },
  goSessionInfo() {
    let that = this;
    wx.navigateTo({
      url: "/pages/mine/personData/personData?goPosterList=1",
    });
    this.setData({
      editDialog: false,
    });
  },
  checkPoster() {
    let that = this;
    let mobile = app.globalData.sessionUser.mobile;
    let res = getApp().globalData.loginUserInfo;
    if (!mobile) {
      this.setData({
        isFirstState: false,
        needShowEdit: true,
      });
      app.mobileReadyCallback && app.mobileReadyCallback(res);
    } else {
      that.selectComponent("#setting").getSessionInfo();
      api.getSessionInfo(null, function (res) {
        let data = res.data.content;
        if (!data.avatar) {
          that.setData({
            editDialog: true,
          });
        } else {
          wx.navigateTo({
            url: "/pages/mine/posterList/posterList",
          });
        }
      });
    }
  },
  closeHold(e) {
    this.setData({
      hold: false,
    });
    app.globalData.hold = false;
  },
  // 打开客服引导
  openkefu() {
    this.setData({
      kefu: true,
      hold: false,
    });
  },
  // 关闭客服引导
  closekefu() {
    this.setData({
      kefu: false,
    });
  },
  // 查看教程
  goCourse() {
    let url = this.data.url;
    let date = this.data.date;
    let title = "房源搬家教程";
    let typename = this.data.typeName;
    wx.navigateTo({
      url:
        "/pages/gatherHouse/playVideo/playVideo?date=" +
        date +
        "&url=" +
        url +
        "&title=" +
        title +
        "&typename=" +
        typename,
    });
  },
  // 将视频连接处理
  CTE(U) {
    let url = U;
    url = url.split("/");
    let pattern = new RegExp("[\u4E00-\u9FA5]+");
    url = url.map((v) => {
      if (pattern.test(v)) {
        v = encodeURIComponent(v);
      }
      return v;
    });
    url = url.join("/");
    return url;
  },
  // 获取所有的视频资源
  queryPmReferenceDetailInfoByRefCode() {
    api.queryPmReferenceDetailInfoByRefCode(
      {
        refCode: "ProductDescription",
      },
      (res) => {
        try {
          let content = res.data.content.map((v) => {
            let refDetailValue = JSON.parse(v.refDetailValue).map((n) => {
              n.url = this.CTE(n.url);
              return n;
            });
            return {
              refDetailName: v.refDetailName,
              refDetailValue: refDetailValue,
            };
          });
          content.map((q) => {
            q.refDetailValue.map((w) => {
              if (w.title == "VR视频采集及分享") {
                this.setData({
                  date: w.date,
                  typeName: w.typeName,
                  url: w.url,
                });
              }
            });
          });
        } catch (error) {
          
        }
      }
    );
  },

  onPageScroll(e) {
    if (this.data.tabConentIndex == 0) {
      this.selectComponent("#home").onScroll(e.scrollTop);
    }
  },

  onShareAppMessage() {
    let sessionUser = getApp().globalData.sessionUser;
    let agentId = sessionUser.id;
    let i = this.data.tabBarObj.findIndex((v) => v.tabBarName == "合作");
    return {
      imageUrl: this.data.tabConentIndex == i ? "/images/cooperation_share.jpg" : "",
      title: this.data.tabConentIndex == i ? "努力打造一个可信赖的合作平台" : "轻松获客—房源素材秒采、端口免费提排名",
      path: `/pages/index/index?tabConentIndex=${this.data.tabConentIndex}&agentId=${agentId}&unionid=${sessionUser.extProps.wechatUnionid}`,
    };
  },
  onReachBottom() {
    if (this.data.tabConentIndex == 0) {
      this.selectComponent("#home").houseListLoadMore();
    }
    if (this.data.tabConentIndex == 3) {
      if (this.selectComponent("#cooperation")) {
        this.selectComponent("#cooperation").onReachBottom();
      }
    }
  },
  onPullDownRefresh() {},

  checkCurrentCity() {
    let t = this;
    t.getCityBe(true).then((city) => {
      if (city) {
        if (city.indexOf("上海") != -1 || city.indexOf("苏州") != -1) {
          t.setData({
            isShowNewCooperation: true,
          });
        } else {
          t.setData({
            isShowNewCooperation: false,
          });
        }
      }
    });
  },

  checkCooperationUserAuth() {
    let t = this;
    return new Promise((resolve, reject) => {
      let sessionUser = getApp().globalData.loginUserInfo.data.content.sessionUser;
      api.queryUserAuthInfo(
        {
          userId: sessionUser.id,
        },
        (res) => {
          if (res && res.data && res.data.content) {
            let isProhibit = res.data.content.canNotCooperation;
            if (isProhibit) {
              t.setData({
                isCooperationUserAuth: false,
              });
              wx.showModal({
                showCancel: false,
                content: "因为合作违规，您的账号已经禁用，若有疑问可以联系平台客服~",
                confirmText: "我知道了",
                confirmColor: "#F75353",
                success(res) {
                  if (res.confirm) {
                    t.goTabBar({
                      currentTarget: {
                        dataset: {
                          index: 0,
                        },
                      },
                    });
                  }
                },
              });
            } else {
              t.setData({
                isCooperationUserAuth: true,
              });
            }
            resolve();
          } else {
            wx.showToast({
              title: "请求失败，请稍后再试~",
              icon: "none",
            });
            reject();
          }
        },
        () => {
          wx.showToast({
            title: "请求失败，请稍后再试~",
            icon: "none",
          });
          reject();
        }
      );
    });
  },

  handleTabChange(e) {
    let index = this.data.tabBarObj.findIndex((v) => v.tabBarName == e.detail);
    let obj = {
      currentTarget: {
        dataset: { index },
      },
    };
    this.goTabBar(obj);
  },

  // 关闭挽留
  handleCloseDetainment() {
    this.setData({
      detainment: false,
      kefu: false,
    });
  },
  // 查看教程
  handleGoCourse() {
    this.setData({ detainment: false });
    let url =
      "/pages/gatherHouse/playVideo/playVideo?date=2020-08-27&url=https://shulan-prod.oss-cn-shanghai.aliyuncs.com/static/jjrjs/WEB%E6%88%BF%E6%BA%90%E6%90%AC%E5%AE%B6/%E4%B8%80%E9%94%AE%E5%8F%91%E6%88%BF.mp4&title=一键发房教程&typename=WEB端教程";
    wx.navigateTo({ url });
  },

  handleOpenKefu() {
    this.setData({
      detainment: false,
      kefu: true,
    });
  },

  onHide: function () {
    app.globalData.lastPage = "/pages/index/index";
  },

  checkTopScanStatus() {
    let wxUserInfo = wx.getStorageSync("user") || {};
    if (this.data.isAuth) return;
    this.setData({
      isAuth: !!(wxUserInfo.nickname && app.globalData.sessionUser.mobile),
    });
  },
});
